import { BrandWCPayRequest } from "@/types/global";

const handleWithWeixinJSBridge = (callback: Function) => {
  if (typeof WeixinJSBridge == "undefined") {
    if (document.addEventListener) {
      // @ts-ignore
      document.addEventListener("WeixinJSBridgeReady", callback, false);
      // @ts-ignore
    } else if (document.attachEvent) {
      // @ts-ignore
      document.attachEvent("WeixinJSBridgeReady", callback);
      // @ts-ignore
      document.attachEvent("onWeixinJSBridgeReady", callback);
    }
  } else {
    callback();
  }
};

export const requestH5Payment = (data: BrandWCPayRequest) =>
  new Promise<any>((resolve, reject) => {
    handleWithWeixinJSBridge(() => {
      WeixinJSBridge.invoke("getBrandWCPayRequest", data, (res) => {
        if (res.err_msg == "get_brand_wcpay_request:ok") {
          // 使用以上方式判断前端返回，微信团队郑重提示：
          //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          resolve(res);
        } else {
          reject(res);
        }
      });
    });
  });
